//
//  CYABDetailPageVC.m
//  CreditAddressBook
//
//  Created by Lee on 15/10/13.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYABDetailPageVC.h"
#import "CYABDetailHeadView.h"
#import "CYABPhoneVC.h"
#import "CYCallRecordsTableVC.h"
#import "DSNavigationBar.h"
#import "CYABDetailStatisticVC.h"
#import "CYStatisticsContentVC.h"
#import "CYStatisticsTopView.h"
#import "CYPerson.h"
#import "LEBarButtonItem.h"
#import "UIImage+ImageEffects.h"
#import "UIInfomationView.h"
#import "CYMeHttpTool.h"
#import "CreditAddressBook-Swift.h"
#import "LEImagePicker.h"
#import "MBProgressHUD+MJ.h"
#import "CYDatabase.h"
#import "CYCollection.h"
#import "CYContacts.h"
#import "CYAddressBookTool.h"
#import "CNMutableContact+Extension.h"
#import "CYCallRecord.h"
#import "CNContact+LE.h"
#import "CYNavigationVController.h"
#import "CYTestVC.h"
#import "CYCreditDetailVC.h"
#import "CYDefaultRecordAO.h"
#import "CYTool.h"

void *CusomHeaderInsetObserver = &CusomHeaderInsetObserver;

@interface CYABDetailPageVC ()<ABPersonViewControllerDelegate>

@property (nonatomic ,strong) CYPerson *person;
@property (nonatomic ,strong) CYCallRecord *callRecord;

@property (nonatomic ,weak) CYABDetailHeadView *detailHeadView;

@property (nonatomic ,weak) CYABPhoneVC *phoneVC;
@property (nonatomic ,weak) CYCallRecordsTableVC *calls;
@property (nonatomic ,weak) CYStatisticsContentVC *statiVC;

@property (nonatomic ,strong) CYCollection *collection;//收藏
@end

@implementation CYABDetailPageVC

- (CYCollection *)collection {
    if (!_collection) {
        _collection = [[CYDatabase sharedDatabase] collectionWithRecordId:[NSString stringWithFormat:@"%@", @(self.person.person.recordID)]].firstObject;
        if (!_collection) {
            CYCollection *collection = [[CYCollection alloc] init];
            collection.phone = self.person.phone;
            collection.name = self.person.name;
            _collection = collection;
        }
    }
    return _collection;
}

- (instancetype)initWithPerson:(CYPerson *)person andCallRecord:(CYCallRecord *)callRecord defrId:(NSString *)recordId {
    //详情
    CYABPhoneVC *phoneVC = [[CYABPhoneVC alloc] init];
    phoneVC.person = person;
    //通话记录
    CYCallRecordsTableVC *calls = [[CYCallRecordsTableVC alloc] init];
    calls.person = person;
    //统计
    CYStatisticsContentVC *statiVC = [[CYStatisticsContentVC alloc] init];
    statiVC.person = person;
    CYStatisticsTopView *topview = [CYStatisticsTopView topView];
    statiVC.topView = topview;
    statiVC.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    if (recordId) {
        //违约详情
        CYCreditDetailVC *credetail = [[CYCreditDetailVC alloc] init];
        CYDefaultRecordAO *defr = [CYDefaultRecordAO new];
        defr.defaultRecordId = recordId;
        defr.type = @"0";
        defr.pushTag = 1;
        credetail.defr = defr;
        self = [super initWithControllers:credetail, phoneVC, calls, statiVC, nil];
    } else {
        self = [super initWithControllers:phoneVC, calls, statiVC, nil];
    }
    
    if (self) {
        self.segmentMiniTopInset = 64;
        self.headerHeight = 250;
        self.person = person;
        self.callRecord = callRecord;
        
        self.phoneVC = phoneVC;
        self.callRecord = callRecord;
        self.statiVC = statiVC;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupOther];
    //通知
    [self setupNotification];
}

- (void)setupOther {
    if (self.person && !self.person.add && self.person.segmentTag != 5) {
        //添加更多按钮
        LEBarButtonItem *itema = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_overflowmenu"] andSelImage:nil andTitle:@"更多" target:self action:@selector(moreBtn)];
        LEBarButtonItem *itema1 = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_star_border_white_48dp"] andSelImage:[UIImage imageNamed:@"ic_star_white_48dp"] target:self action:@selector(collectionBtn:)];
        
        if (self.collection.recordId) {
            itema1.selected = YES;
        }
        
        self.navigationItem.rightBarButtonItems = @[itema, itema1];
    } else if (self.person && self.person.add) {
        //保存陌生号码
        UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(addPerson)];
        barBtn.tintColor = CYNaviTitleColor;
        self.navigationItem.rightBarButtonItem = barBtn;
    }
    
    [self addObserver:self forKeyPath:@"segmentToInset" options:NSKeyValueObservingOptionNew context:CusomHeaderInsetObserver];
}
/**
 *  更多
 */
- (void)moreBtn {
    [self.view endEditing:YES];
    //创建action
    [UIInfomationView showActionSheetInView:self.view WithTitle:nil cancelButtonTitle:@"返回" destructiveButtonTitle:nil otherButtonTitles:@[@"修改"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex == 1) {//修改
            [self changeBtn];
        } else if (buttonIndex == 2) {//收藏
            // [self DeleteBtn];
            [self test];
        }
    }];
}

- (void)changeBtn {
//    [CYAddressBookTool ABPersonViewController:self person:self.person.person completion:^(id obj) {
//        CYLog(@"person");
//    }];
     
     
//    [[CYAddressBookTool new] ABPersonViewController:self person:self.person.person completion:^(id obj) {
//        CYLog(@"person");
//    }];
     
     
     ABPersonViewController *personController = [[ABPersonViewController alloc]init];
     
     [self.navigationController pushViewController:personController animated:YES];
     
     personController.displayedPerson = self.person.person.recordRef;
     //设置代理
     personController.personViewDelegate = self;
     
//     [personController setDisplayedPerson:self.person.person.recordRef];
//     
//     [personController setEditing:YES];
//     
//     [personController setAllowsActions:YES];
//     
//     [personController setAllowsEditing:YES];
//    [CYAddressBookTool newPersonWithController:self person:[CYContacts autoContactsWithPerson:self.person.person] completion:^(id obj) {
//        [self reloadAbtableViewDataSource];
//        [self.abTableView reloadData];
//    }];
}



#pragma mark - 添加陌生号码
/**
 *  添加陌生号码
 */
- (void)addPerson {
    [self.view endEditing:YES];
    [UIInfomationView showActionSheetInView:self.view WithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"新建联系人", @"添加到现有联系人"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex == CYIndexSecond) {//新建联系人
            RHPerson *rhPerson = self.person.person;
            NSString *phone = rhPerson.phoneNumbers.values.firstObject;
            
            CYContacts *contacts = [[CYContacts alloc] init];
            if (phone) {
                contacts.person = rhPerson;
#if IS_IOS9
                CNMutableContact *muContact = [[CNMutableContact alloc] init];
                muContact.imageData = nil;
                muContact.phones = @[phone];
                contacts.contact = muContact;
#endif
                
            }
            [CYAddressBookTool newPersonWithController:self person:contacts completion:^(id obj) {
                //联系人添加成功后的操作
                [self addSuccess:obj];
                [self.navigationController popViewControllerAnimated:NO];
                
            }];
        } else if (buttonIndex == CYIndexThird) {//添加到现有联系人
            [CYAddressBookTool addressBookUIPickerWithController:self edit:YES completion:^(id obj) {
                RHPerson *rhPerson = self.person.person;
                NSString *phone = rhPerson.phoneNumbers.values.firstObject;
                if (phone) {
                    CYContacts *contacts = [CYContacts contactsWithPerson:obj];
                    if (contacts.person) {
                        RHMutableMultiStringValue *value = contacts.person.phoneNumbers.mutableCopy;
                        [value addValue:phone withLabel:RHPersonPhoneIPhoneLabel];
                        contacts.person.phoneNumbers = value;
                    } else if (contacts.contact) {
#if IS_IOS9
                        CNMutableContact *muContact = contacts.contact.mutableCopy;
                        muContact.phones = @[phone];
                        contacts.contact = muContact;
#endif
                    }
                    [CYAddressBookTool newPersonWithController:self person:contacts completion:^(id obj) {
                        //联系人添加成功后的操作
                        [self addSuccess:obj];
                        [self.navigationController popViewControllerAnimated:NO];
                    }];
                }
            }];
        }
    }];
}

/**
 *  联系人添加成功后的操作
 */
- (void)addSuccess:(id)obj {
    CYContacts *contacts = [CYContacts contactsWithPerson:obj];
    if (contacts.person) {
        self.callRecord.callHistory.name = contacts.person.name;
        self.callRecord.callHistory.recordID = contacts.person.recordID;
    } else if (contacts.contact) {
#if IS_IOS9
        self.callRecord.callHistory.name = contacts.contact.name;
        self.callRecord.callHistory.identifier = contacts.contact.identifier;
#endif
        
    }
    //将动物头像去除掉
    self.callRecord.callHistory.headImageName = nil;
    [self.callRecord.callHistory update];
    //发出通知更新通话记录显示
    [CYNotificationCenter postNotificationName:CYCallRecordChangeNotification object:nil];
}

#pragma mark - 滚动监听
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    if (context == CusomHeaderInsetObserver) {
        CGFloat topInset = [change[NSKeyValueChangeNewKey] floatValue];
        
        if (topInset <= self.segmentMiniTopInset) {
            self.title = self.person.name;
//            self.headerView.imageView.image = self.blurImage;
//            self.headerView.alpha = 0;
        }else{
            self.title = nil;
        }
        //设置导航栏颜色变化
        CGFloat alpha = (topInset - 64)/self.headerHeight;
        if (alpha < .0) {
            alpha = .0;
        } else if (alpha > .7) {
            alpha = .996;
        }
        [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYNaviThemeColorWithAlpha(0.996 - alpha)];
//        self.headerView.alpha = alpha;
    }
}

#pragma mark - override 自定义头部图片
-(UIView<ARSegmentPageControllerHeaderProtocol> *)customHeaderView {
    CYABDetailHeadView *view = [CYABDetailHeadView detailHeadView];
    self.detailHeadView = view;
    if (self.person) {
        if (self.person.person.thumbnail) {
            view.imageView.image = self.person.person.thumbnail;
        }
        view.nameLabel.text = self.person.name;
        if (self.person.person.note) {
            view.noteLabel.text = self.person.person.note;
        } else {
            view.noteLabel.text = @"空";
        }
    }
    [view.changeHeadBtn addTarget:self action:@selector(changeHeadBtn:) forControlEvents:UIControlEventTouchDown];
//    [view.collectionBtn addTarget:self action:@selector(collectionBtn:) forControlEvents:UIControlEventTouchDown];
    if (self.collection.recordId) {
        view.collectionBtn.selected = YES;
    }
    
    return view;
}

/**
 *  更改头像按钮
 */
- (void)changeHeadBtn:(UIButton *)sender {
    [self.view endEditing:YES];
    [UIInfomationView showActionSheetInView:self.view WithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"相机", @"从相册中选取"] clickAtIndex:^(NSInteger buttonIndex) {
        [self didDismissAlert:nil withButtonAtIndex:buttonIndex];
    }];
}

/**
 *  收藏按钮
 */
- (void)collectionBtn:(UIButton *)sender {
    BOOL result = false;
    if (sender.selected) {
        //取消收藏
        result = [[CYDatabase sharedDatabase] deleteCollectionWithId:self.collection.collectionId];
    } else {
        //添加收藏
        self.collection.recordId = [NSString stringWithFormat:@"%@", @(self.person.person.recordID)];
        result = [[CYDatabase sharedDatabase] addCollection:self.collection];
    }
    if (result) {
        sender.selected = sender.selected ? NO: YES;
        //发出通知更新收藏数据显示
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CYCollectionNotification" object:nil userInfo:nil];
    }
}

/**
 *  UIAlertController dismiss
 *
 *  @param alertView
 *  @param buttonIndex
 */
- (void)didDismissAlert:(id)alertView withButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == CYIndexSecond) {
        [LEImagePicker imageFromCameraWithController:self completion:^(UIImage *image) {
            [self setupImage:image];
        }];
    } else if (buttonIndex == CYIndexThird) {
        [LEImagePicker imageFromPhotoLibraryWithController:self completion:^(UIImage *image) {
            [self setupImage:image];
        }];
    } else if (buttonIndex == CYIndexFourth) {
        CYBlackAppImageVC *blackApp = [CYBlackAppImageVC xc_loadFromNibUsingClassName];
        blackApp.person = self.person;
        blackApp.callRecord = self.callRecord;
        [self.navigationController pushViewController:blackApp animated:YES];
    }
    
}

- (void)setupImage:(UIImage *)image {
    RHPerson *person = self.person.person;
    [person setImage:image];
    [person save];
    self.detailHeadView.imageView.image = image;
    [MBProgressHUD showSuccess:@"修改成功"];
}

#pragma mark - 方法重写
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:[UIColor clearColor]];
    [self.view endEditing:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:[UIColor clearColor]];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYNaviThemeColor];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYNaviThemeColor];
}

#pragma mark - 通知
- (void)setupNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneaddressBookChanged:) name:RHAddressBookExternalChangeNotification object:nil];
}

//联系人详情信息通知
- (void)phoneaddressBookChanged:(NSNotification *)notifi{
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    
    RHPerson *phoneperson = [self.person.person.addressBook personForABRecordID:self.person.person.recordID];
    self.person.person = phoneperson;
    //头像
    if (phoneperson.thumbnail) {
        self.detailHeadView.imageView.image = phoneperson.thumbnail;
    }
    //姓名
    self.detailHeadView.nameLabel.text = phoneperson.name;
    //备注
    if (phoneperson.note && phoneperson.note.length) {
        self.detailHeadView.noteLabel.text = phoneperson.note;
    }
    [self.phoneVC reloadPerson:self.person];
}

-(void)dealloc {
    CYLog(@"详情页销毁");
    [self removeObserver:self forKeyPath:@"segmentToInset"];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RHAddressBookExternalChangeNotification" object:nil];
}

- (void)test {
    CYTestVC *v = [CYTestVC xc_loadFromNibUsingClassName];
    [self.navigationController pushViewController:v animated:YES];
}

@end
